package com.yc.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.yc.annotation.AnonymousAccess;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Bean
    public IgnoreUrlsConfig ignoreUrlsConfig() {
        return new IgnoreUrlsConfig();
    }

    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> ignoreUrls = ignoreUrlsConfig().getUrls();
        registry.addInterceptor(new SaInterceptor(handler -> {
                    //搜寻匿名标记 url： @AnonymousAccess
                    if (handler.getClass().equals(HandlerMethod.class)) {
                        HandlerMethod handlerMethod = (HandlerMethod) handler;
                        if (handlerMethod.hasMethodAnnotation(AnonymousAccess.class)) {
                            SaRouter.stop();
                        }
                        SaRouter.match(Collections.singletonList("/**")).check(StpUtil::checkLogin);
                    }

                }) {
                    @SuppressWarnings("all")
                    @Override
                    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

                    }
                })
                .addPathPatterns("/**")
                .excludePathPatterns(ignoreUrls);
        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
    }
}
